﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdmLaboratorios.DAO;
using AdmLaboratorios.Business.Entities;
using AdmLaboratorios.DTO;
using System.Data.SqlClient;

namespace AdmLaboratorios.Business
{
    public static class BusinessHelper
    {
        static GrillaColumnaDAO grillaColumnaDAO = DAOFactory.Get<GrillaColumnaDAO>();

        public static Usuario Usuario { get; set; }

        public static void SetUserName(string nombreDeUsuario)
        {
            DAOFactory.NombreDeUsuario = nombreDeUsuario;
        }

        public static void Log(string msg)
        {
            using (SqlTransaction tran = grillaColumnaDAO.IniciarTransaccion())
            {
                grillaColumnaDAO.Log(LogDTO.eAcciones.Excepcion, msg, 0, tran, "");
                grillaColumnaDAO.CommitTransaccion(tran);
            }
        }

        internal static string GetIP()
        {
            var hostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            return (from addr in hostEntry.AddressList
                    where addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                    select addr.ToString()
                    ).FirstOrDefault();
        }

        public static decimal Truncate2Decimals(decimal value)
        {
            if (value != 0)
                return Math.Truncate(value * 100) / 100;
            else
                return 0;
        }

        public static decimal Redondeo(decimal aux)
        {
            if (aux == 0m)
                return 0m;

            decimal decimalPart = Math.Truncate(aux) - Truncate2Decimals(aux);
            if (decimalPart < -0.5m)
                return 1 + decimalPart;
            else
                return decimalPart;
        }
        
        public static void SetGrillaColumnas(List<GrillaColumnaDTO> columnas)
        {
            using (SqlTransaction tran = grillaColumnaDAO.IniciarTransaccion())
            {
                try
                {
                    grillaColumnaDAO.Delete(string.Format("Formulario = '{0}' AND Grilla = '{1}'", columnas[0].Formulario, columnas[0].Grilla), tran);
                    foreach (GrillaColumnaDTO columna in columnas)
                    {
                        grillaColumnaDAO.Create(columna, tran);
                    }
                    grillaColumnaDAO.CommitTransaccion(tran);
                }
                catch (Exception)
                {
                    grillaColumnaDAO.RollbackTransaccion(tran);
                    throw;
                }
            }
        }
        
        public static List<GrillaColumnaDTO> GetGrillaColumnas()
        {
            return grillaColumnaDAO.ReadAll();
        }

    }
}
